$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'orth/courseManage/list',
        datatype: "json",
        colModel: [
            { label: '图片', name: 'picture',sortable:false, width: 80, formatter: function(value, options, row){

                return    value==undefined || value==null || value=="" ? '<image src="/statics/img/noImage.png" style="width: 50%; height: auto;max-width: 50%; display: block;"></image>' : '<image src="'+value+'" style="width: 50%; height: auto;max-width: 50%; display: block;"></image>';
            }},
			{ label: '用户ID', name: 'id_', index: "id_", width: 35, key: true,hidden:true },
			{ label: '简介', name: 'digest', width: 75 },
            { label: '开始时间', name: 'startTime', width: 75,formatter: function(value, options, row){
                return value != undefined && value!=null && value!="" ? value.split(" ")[0]:"";
            }},
			{ label: '类型', name: 'type', width: 90,formatter: function(value, options, row){
                return value === 0 ?
                    '预告' :
                    '回顾';
            }},
			{ label: '更新时间', name: 'updateTime', width: 80,sortable:false}
        ],
		viewrecords: true,
        
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    $('.form-horizontal').validationEngine('attach',{
        autoHidePrompt: true,
        autoHideDelay: 2000,
        maxErrorsPerField: 1
    });



});


function uploadImage(id,name)
{


    $(id).fileupload({
        url: baseURL + "fileUpload/image",
        type: "POST",
        autoUpload: true,
        /*formData:{desc:$("#ed_desc").val()},*/
        sequentialUploads: true
    }).bind('fileuploadprogress', function (e, data) {
        //$("#down_div").removeClass("xhide");
        // $("#over_div").removeClass("xhide");

        if(name=="picture")
            vm.picture = data.originalFiles[0].name;

    }).bind('fileuploaddone', function (e, data) {
        // $("#down_div").addClass('xhide');
        // $("#over_div").addClass('xhide');
        if(data.result.errcode==0){
            //$("#upload").val(data.result.data);

            if(name=="picture")
                vm.course.picture = data.result.data;

            alert("上传成功！");
        }else{
            alert("上传失败！");
        }

    });


}

Vue.component('v-select', VueSelect.VueSelect);

/*var vue_selected=new Vue({
    el: '#app',
    data: function() {
        return {
            options: [
                {"student_id": 1, "name": "Vence"},
                {"student_id": 2, "name": "Job"},
                {"student_id": 3, "name": "Jack"},
            ],
            placeholder: 'Choose a student..',
            students: [1],
            student_obj: []
        }
    },
    mounted: function() {
        var student_filter = function (obj) {
            return this.students.indexOf(obj.student_id) > -1
        }
        this.student_obj = this.options.filter(student_filter, this)
    },
    methods:{
        selecte_student: function(values){
            this.students =values.map(function(obj){
                return obj.student_id
            })
        }
    }
});*/

var myFilter;

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			content: null
		},
        requestUrl:baseURL+"fileUpload/image",
        token:{token:localStorage.getItem("token")},
		picture:"",
		showList: true,
		title:null,
        course:{
			status:0,
			teamMembers:'',
            ygId:'',
            startTime:'',
            endTime:''
		},
        options: [],
        placeholder: '选择课程讲师..',
        experts: [],
        expert_obj: [],
        isShow:false,  //可选预告课程列表是否显示
        preview_course:[]  //保存可选预告课程列表
	},
    mounted: function() {

        var expert_filter = function (obj) {
            return this.experts.indexOf(obj.expert_id) > -1
        }
        myFilter=expert_filter;
        $.ajax({
            type: "POST",
            url: baseURL + "orth/courseManage/getMembers",
            contentType: "application/json",
            success: function(r){
                if(r.code == 0){
                    vm.options=r.members;

                }else{
                    alert(r.msg);
                }
            }
        });
        this.expert_obj = this.options.filter(expert_filter, this);

    },
	methods: {
        selecte_expert: function(values){
            this.experts =values.map(function(obj){
                return obj.expert_id
            })
        },
        courseChanged:function () {
            console.log("取到的值是"+vm.course.type);
            //显示隐藏控件
            if(vm.course.type==1)
            {

               vm.isShow=true;
               //获取可选预告课程
               vm.getPreviewCourse();

            }else
            {
                vm.isShow=false;
                vm.course.ygId=null;
            }


        },
        handlePreview0(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG或者PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        handleAvatarSuccess0(res, file) {
            vm.picture=res.data;
        },
		query: function () {
            jQuery("#jqGrid").jqGrid('setGridParam',{page:1});
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.course = {status:0,type:0,dayText:"半天",startTime:'',endTime:'',title:'',subtitle:''};
			vm.experts=[];
            vm.expert_obj=[];
            vm.isShow=false;
            vm.picture="";
            um.setContent("");

		},
		update: function () {
			var userId = getSelectedRow();
			if(userId == null){
				return ;
			}
			
			vm.showList = false;
            vm.title = "修改";
			vm.getUser(userId);

		},
		del: function () {
			var userIds = getSelectedRows();
			if(userIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "orth/courseManage/delete",
                    contentType: "application/json",
				    data: JSON.stringify(userIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(){
                                vm.reload();
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		saveOrUpdate: function () {

            if(!$(".form-horizontal").validationEngine("validate")) {
                $(".formError").show();
                return;
            }
            /*if(vm.validator()){
                return ;
            }*/
          //  超过当前日期的就没法选择了。var now = new Date();比如跟明天比now > new Date(2016,6,7)可以直接得出false。。
            /* vm.course.id_ == null ? vm.course.teamMembers=vm.experts.join(",") : vm.experts=vm.course.teamMembers.split(",");*/
           if(vm.course.startTime=='')
           {
               alert("请选择开始日期");
               return;
           }
            if(vm.course.endTime=='')
            {
                alert("请选择结束日期");
                return;
            }
            if(vm.course.type==1)
            {
                if(vm.course.ygId=='')
                {
                    alert("请选择预告课程");
                    return;
                }
            }

           vm.course.picture=vm.picture;
           if(vm.course.picture=="")
           {
               alert("请添加课程图片");
               return;
           }
           vm.course.teamMembers=vm.experts.join(",");
           if(vm.course.teamMembers==null || vm.course.teamMembers=='')
           {
               alert("请选择课程讲师");
               return;
           }

            var count=um.getContentTxt().length;
            if(count>10000)
            {
                alert("内容最大10000字符");
                return;
            }
            var content=um.getContent();
            vm.course.content=um.getContent();
            if(vm.course.content!=null && vm.course.content.length>0)
            {
                var reg1 = new RegExp( '<' , "g" );
                var reg2 = new RegExp( '>' , "g" );
                vm.course.content=vm.course.content.replace( reg1,'88888888qzpm' );
                vm.course.content=vm.course.content.replace( reg2,'99999999qzpm' );
            }

			var url = vm.course.id_ == null ? "orth/courseManage/save" : "orth/courseManage/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.course),//JSON.stringify(vm.course)
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
        setSelectedExperts:function (obj) {

            return this.experts.indexOf(obj.expert_id) > -1

        },
		getUser: function(id){
			$.get(baseURL + "orth/courseManage/info/"+id, function(r){
				vm.course = r.course;
				vm.picture=vm.course.picture;
				var temp=r.course.teamMembers.split(",");
                vm.experts=temp.map(function(data){
                    return +data;
                });
                vm.expert_obj = vm.options.filter(vm.setSelectedExperts,this);
                um.setContent(vm.course.content);
                vm.course.startTime=vm.setDate(vm.course.startTime);
                vm.course.endTime=vm.setDate(vm.course.endTime);
                if(vm.course.type==1)
                {
                    vm.isShow=true;
                    vm.getPreviewCourse(vm.course.id_,r.course.ygId);
                }else
                    vm.isShow=false;
            });
		},

		getRoleList: function(){
			$.get(baseURL + "sys/role/select", function(r){
				vm.roleList = r.list;
			});
		},
		reload: function () {
			vm.showList = true;
            $(".formError").hide();
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                postData:{'content': vm.q.content},
                page:page
            }).trigger("reloadGrid");
		},
        setDate:function (obj) {
            return obj!=undefined && obj!=null && obj!="" ? obj.split(" ")[0]:"";

        },
        getPreviewCourse:function(id,ygId){

		    var url=baseURL + "orth/courseManage/getCoursees";
		    if(id!=undefined)
            {
                url+="?id="+id;
            }
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                success: function(r){
                    if(r.code == 0){
                        vm.preview_course=r.coursees;
                        if(ygId!=undefined)
                        vm.course.ygId=ygId;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        validator: function () {

        }
	}
});

